<?php

use control\interfaces;

require_once 'interface.php';

class qyLoginClass
{
	use interfaces;

	private string $userId;  //企业微信userId
	private string $msg;     //错误信息
	private string $deviceId;//登录设备ID;

	private function qyToken(): bool
	{
		$appid = $this->get('appid');
		$did   = $this->get('did');
		$code  = $this->get('code');
		if ($appid != para('qyWeChatCorpid')) {
			$this->msg = 'appId与企业Corpid不一致';
			return false;
		}
		$token  = wechatToken('qyLoginToken');
		$result = self::curlGet('https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=' . $token . '&code=' . $code);
		$res    = json_decode($result, true);
		if ($res['errcode'] != 0) {
			$this->msg = $res['errmsg'];
			return false;
		} else {
			$this->deviceId = $did ?? '';
			$this->userId   = $res['UserId'];
			return true;
		}
	}

	public function login(): bool|string
	{
		$bool = $this->qyToken();
		if (!$bool) {
			return $this->msg;
		} else {
			$user = query('user', "weChatUserId = '" . $this->userId . "'");
			if (empty($user['uid'])) {
				return '未找到用户';
			} elseif ($user['state'] == "停用") {
				return "您的账号处于停用状态，请联系行政人员！";
			} else {
				//登录密码错误次数清零
				update([
					"table" => "user",
					"field" => [
						'loginError' => 0,
						'deviceId'   => $this->deviceId,
					],
					"where" => " uid = '" . $user['uid'] . "' ",
				]);
                $record = query('user_setting', "stid = '" . $user['stid'] . "' and type = '当前使用账套'");
				//添加登录记录
				insert([
					"table" => "log",
					"field" => [
						"type" => "user",
                        "coid" => $record['value'],
						"stid" => $user['stid'],
						"text" => $user['name'] . "扫码登录了管理员后台，ip地址：" . getIp(),
						"time" => date("Y-m-d H:i:s"),
					],
				]);
				//创建登录session，返回跳转地址
				$_SESSION['stid']     = $user['stid'];
				$_SESSION['deviceId'] = $this->deviceId;
				return true;
			}
		}
	}
}

$login = new qyLoginClass();
$res   = $login->login();
if ($res === true) {
	header("Location:" . root . 'control/adIndex.html');
} else {
	echo $res;
}
